package com.xuecheng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.dto.MyCourseTableParamsDTO;
import com.xuecheng.exception.CommonError;
import com.xuecheng.exception.XueChengPlusException;
import com.xuecheng.feignclient.ContentServiceClient;
import com.xuecheng.mapper.XcChooseCourseMapper;
import com.xuecheng.mapper.XcCourseTablesMapper;
import com.xuecheng.model.PageResult;
import com.xuecheng.po.CoursePublish;
import com.xuecheng.po.XcChooseCourse;
import com.xuecheng.po.XcCourseTables;
import com.xuecheng.service.MyCourseTablesService;
import com.xuecheng.vo.MyCourseTableItemVO;
import com.xuecheng.vo.XcChooseCourseVO;
import com.xuecheng.vo.XcCourseTablesVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {
	
	@Resource
	private XcChooseCourseMapper xcChooseCourseMapper;
	@Resource
	private XcCourseTablesMapper xcCourseTablesMapper;
	@Resource
	private ContentServiceClient contentServiceClient;
	@Resource
	private MyCourseTablesServiceImpl myCourseTablesService;
	
	@Override
	public XcChooseCourseVO addChooseCourse(String userId, Long courseId) {
		//查询课程信息
		CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
		if (coursepublish == null) {
			XueChengPlusException.cast("课程信息不存在");
		}
		Long id = coursepublish.getId();
		if (id == null) {
			XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
		}
		//课程收费标准
		String charge = coursepublish.getCharge();
		
		XcChooseCourse xcChooseCourse = null;
		if (charge.equals("201001")) {
			//添加收费课程
			xcChooseCourse = myCourseTablesService.addChargeCoruse(userId, coursepublish);
		} else {
			//添加免费课程
			xcChooseCourse = myCourseTablesService.addFreeCoruse(userId, coursepublish);
		}
		
		
		XcChooseCourseVO xcChooseCourseDto = new XcChooseCourseVO();
		BeanUtils.copyProperties(xcChooseCourse, xcChooseCourseDto);
		//获取学习资格
		XcCourseTablesVO xcCourseTablesVO = getLeanringStatus(userId, courseId);
		xcChooseCourseDto.setLearnStatus(xcCourseTablesVO.getLearnStatus());
		return xcChooseCourseDto;
	}
	
	
	/**
	 * 判断学习资格
	 */
	public XcCourseTablesVO getLeanringStatus(String userId, Long courseId) {
		XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
		if (xcCourseTables == null) {
			XcCourseTablesVO xcCourseTablesVO = new XcCourseTablesVO();
			xcCourseTablesVO.setLearnStatus("702002");   //没有学习资格
			return xcCourseTablesVO;
		}
		XcCourseTablesVO xcCourseTablesVO = new XcCourseTablesVO();
		BeanUtils.copyProperties(xcCourseTables, xcCourseTablesVO);
		//是否过期,true过期，false未过期
		boolean isExpires = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
		if (!isExpires) {
			//正常学习
			xcCourseTablesVO.setLearnStatus("702001");
			
		} else {
			//已过期
			xcCourseTablesVO.setLearnStatus("702003");
		}
		return xcCourseTablesVO;
		
	}
	
	@Override
	public boolean saveChooseCourseStauts(String choosecourseId) {
		XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(choosecourseId);
		if (xcChooseCourse != null) {
			String status = xcChooseCourse.getStatus();
			if ("701002".equals(status)) {//待支付
				//更新为选课成功
				xcChooseCourse.setStatus("701001");
				int update = xcChooseCourseMapper.updateById(xcChooseCourse);
				//添加到课程表
				addCourseTabls(xcChooseCourse);
				if (update > 0) {
					log.info("收到支付结果通知处理成功,选课记录:{}", xcChooseCourse);
					return true;
				} else {
					log.error("收到支付结果通知处理失败,选课记录:{}", xcChooseCourse);
					return false;
				}
			} else {
				log.info("收到支付结果通知已经处理,选课记录:{}", xcChooseCourse);
				return true;
			}
		} else {
			log.error("收到支付结果通知没有查询到关联的选课记录,choosecourseId:{}", choosecourseId);
		}
		return false;
	}
	
	public PageResult<MyCourseTableItemVO> mycourestabls(MyCourseTableParamsDTO params) {
		
		int page = params.getPage();
		int size = params.getSize();
		int startIndex = (page - 1) * size;
		params.setStartIndex(startIndex);
		
		List<MyCourseTableItemVO> myCourseTableItemDTOS = xcCourseTablesMapper.myCourseTables(params);
		int total = xcCourseTablesMapper.myCourseTablesCount(params);
		
		
		PageResult<MyCourseTableItemVO> pageResult = new PageResult<>();
		pageResult.setItems(myCourseTableItemDTOS);
		pageResult.setCounts(total);
		pageResult.setPage(page);
		pageResult.setPageSize(size);
		return pageResult;
		
	}
	
	/**
	 * 添加到我的课程表
	 */
	@Transactional
	public XcCourseTables addCourseTabls(XcChooseCourse xcChooseCourse) {
		//选课记录完成且未过期可以添加课程到课程表
		String status = xcChooseCourse.getStatus();
		if (!"701001".equals(status)) {
			XueChengPlusException.cast("选课记录未完成，无法添加到课程表");
		}
		//查询我的课程表
		XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
		if (xcCourseTables != null) {
			LocalDateTime validtimeEnd = xcChooseCourse.getValidtimeEnd();
			if (xcCourseTables.getValidtimeEnd().isAfter(validtimeEnd)) {
				//如果我的课程表中的过期时间比新订单的过期时间靠后，不用更新课程表。
				return xcCourseTables;
			} else {
				//更新我的课程表
				xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
				xcCourseTables.setUpdateDate(LocalDateTime.now());
				xcCourseTables.setValidtimeStart(xcChooseCourse.getValidtimeStart());
				xcCourseTables.setValidtimeEnd(xcChooseCourse.getValidtimeStart());
				xcCourseTables.setCourseType(xcChooseCourse.getOrderType());
				xcCourseTablesMapper.updateById(xcCourseTables);
				return xcCourseTables;
			}
		}
		XcCourseTables xcCourseTablesNew = new XcCourseTables();
		xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getId());
		xcCourseTablesNew.setUserId(xcChooseCourse.getUserId());
		xcCourseTablesNew.setCourseId(xcChooseCourse.getCourseId());
		xcCourseTablesNew.setCompanyId(xcChooseCourse.getCompanyId());
		xcCourseTablesNew.setCourseName(xcChooseCourse.getCourseName());
		xcCourseTablesNew.setCreateDate(LocalDateTime.now());
		xcCourseTablesNew.setValidtimeStart(xcChooseCourse.getValidtimeStart());
		xcCourseTablesNew.setValidtimeEnd(xcChooseCourse.getValidtimeEnd());
		xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType());
		xcCourseTablesMapper.insert(xcCourseTablesNew);
		
		return xcCourseTablesNew;
		
	}
	
	/**
	 * 根据课程和用户查询我的课程表中某一门课程
	 */
	public XcCourseTables getXcCourseTables(String userId, Long courseId) {
		return xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId,
			userId).eq(XcCourseTables::getCourseId, courseId));
		
	}
	
	@Transactional
	//添加免费课程,免费课程加入选课记录表、我的课程表
	public XcChooseCourse addFreeCoruse(String userId, CoursePublish coursepublish) {
		//查询选课记录表是否存在免费的且选课成功的订单
		LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper = queryWrapper.eq(XcChooseCourse::getUserId, userId)
			.eq(XcChooseCourse::getCourseId, coursepublish.getId())
			.eq(XcChooseCourse::getOrderType, "700001")//免费订单
			.eq(XcChooseCourse::getStatus, "701001");//选课成功
		List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
		if (xcChooseCourses != null && !xcChooseCourses.isEmpty()) {
			return xcChooseCourses.get(0);
		}
		//添加选课记录信息
		XcChooseCourse xcChooseCourse = new XcChooseCourse();
		xcChooseCourse.setCourseId(coursepublish.getId());
		xcChooseCourse.setCourseName(coursepublish.getName());
		xcChooseCourse.setCoursePrice(0f);//免费课程价格为0
		xcChooseCourse.setUserId(userId);
		xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
		xcChooseCourse.setOrderType("700001");//免费课程
		xcChooseCourse.setCreateDate(LocalDateTime.now());
		xcChooseCourse.setStatus("701001");//选课成功
		
		xcChooseCourse.setValidDays(365);//免费课程默认365
		xcChooseCourse.setValidtimeStart(LocalDateTime.now());
		xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
		xcChooseCourseMapper.insert(xcChooseCourse);
		//添加到我的课程表
		addCourseTabls(xcChooseCourse);
		return xcChooseCourse;
		
	}
	
	@Transactional
	//添加收费课程
	public XcChooseCourse addChargeCoruse(String userId, CoursePublish coursepublish) {
		
		//如果存在待支付记录直接返回
		LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper = queryWrapper.eq(XcChooseCourse::getUserId, userId)
			.eq(XcChooseCourse::getCourseId, coursepublish.getId())
			.eq(XcChooseCourse::getOrderType, "700002")//收费订单
			.eq(XcChooseCourse::getStatus, "701002");//待支付
		List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
		if (xcChooseCourses != null && !xcChooseCourses.isEmpty()) {
			return xcChooseCourses.get(0);
		}
		
		XcChooseCourse xcChooseCourse = new XcChooseCourse();
		xcChooseCourse.setCourseId(coursepublish.getId());
		xcChooseCourse.setCourseName(coursepublish.getName());
		xcChooseCourse.setCoursePrice(coursepublish.getPrice());//免费课程价格为0
		xcChooseCourse.setUserId(userId);
		xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
		xcChooseCourse.setOrderType("700002");//收费课程
		xcChooseCourse.setCreateDate(LocalDateTime.now());
		xcChooseCourse.setStatus("701002");//待支付
		
		xcChooseCourse.setValidDays(coursepublish.getValidDays());
		xcChooseCourse.setValidtimeStart(LocalDateTime.now());
		xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));
		xcChooseCourseMapper.insert(xcChooseCourse);
		return xcChooseCourse;
	}
	
}
